rm(list=ls())
library(tidyverse)
library(plyr)
library(scales)
library(dplyr)
library(rmeta)
library(xtable)


# This script outputs:
  # Figures 2, 3, 
  # Tables 1, 2


states = tolower(c("AL", "AR", "CA", "CT", "FL", "IL", "IN", "KS", "KY", "MA", "MD",
                   "MO",
                   "NE", "NV", "NY", "OH", "OR", "PA", "RI", "SC", "TN", "TX", "VA", "WA",
                   "WV"))



results = as.data.frame(matrix(nrow = 0, ncol = 7))
colnames(results) = c("coef", "se", "race", "dv", "p value", "endog", "state")



for(state in states){
  f = paste0('results/results_',state,'.Rdata')
  
  load(f)
  holder = as.data.frame(matrix(nrow = 36, ncol = 7))
  colnames(holder) = c("coef", "se", "race", "dv", "p value", "endog", "state")
  
  holder$coef = c(ivmod1_white$cace, ivmod1_black$cace, ivmod1_hispanic$cace,
                   ivmod2_white$cace,  ivmod2_black$cace, ivmod2_hispanic$cace,
                   ivmod3_white$cace,  ivmod3_black$cace, ivmod3_hispanic$cace,
                   ivmod4_white$cace,  ivmod4_black$cace, ivmod4_hispanic$cace,
                   ivmod5_white$cace,  ivmod5_black$cace, ivmod5_hispanic$cace,
                   ivmod6_white$cace,  ivmod6_black$cace, ivmod6_hispanic$cace,
                   ivmod_rep_white$cace,  ivmod_rep_black$cace, ivmod_rep_hispanic$cace,
                  
                   
                   
                  ivmod1_white_f12$cace,  ivmod1_black_f12$cace, ivmod1_hispanic_f12$cace,
                   ivmod2_white_f12$cace,  ivmod2_black_f12$cace, ivmod2_hispanic_f12$cace,
                    ivmod5_white_f12$cace,  ivmod5_black_f12$cace, ivmod5_hispanic_f12$cace,
                    ivmod6_white_f12$cace,  ivmod6_black_f12$cace, ivmod6_hispanic_f12$cace,
                    ivmod_rep_white_f12$cace,  ivmod_rep_black_f12$cace, ivmod_rep_hispanic_f12$cace
                   
                   
                   
                   
                   
                   )
  
  holder$se = c(ivmod1_white$se,  ivmod1_black$se, ivmod1_hispanic$se,
                ivmod2_white$se,  ivmod2_black$se, ivmod2_hispanic$se,
                ivmod3_white$se,  ivmod3_black$se, ivmod3_hispanic$se,
                ivmod4_white$se,  ivmod4_black$se, ivmod4_hispanic$se,
                ivmod5_white$se,  ivmod5_black$se, ivmod5_hispanic$se,
                ivmod6_white$se,  ivmod6_black$se, ivmod6_hispanic$se,
                ivmod_rep_white$se,  ivmod_rep_black$se, ivmod_rep_hispanic$se,
                
                
                
               ivmod1_white_f12$se,  ivmod1_black_f12$se, ivmod1_hispanic_f12$se,
               ivmod2_white_f12$se,  ivmod2_black_f12$se, ivmod2_hispanic_f12$se,
                ivmod5_white_f12$se,  ivmod5_black_f12$se, ivmod5_hispanic_f12$se,
                ivmod6_white_f12$se,  ivmod6_black_f12$se, ivmod6_hispanic_f12$se,
                ivmod_rep_white_f12$se,  ivmod_rep_black_f12$se, ivmod_rep_hispanic_f12$se
                
                
                
                 
                 
                 
  )
  
  holder$`p value` = c(ivmod1_white$summary$coefficients[2,4],  ivmod1_black$summary$coefficients[2,4], ivmod1_hispanic$summary$coefficients[2,4],
                       ivmod2_white$summary$coefficients[2,4],  ivmod2_black$summary$coefficients[2,4], ivmod2_hispanic$summary$coefficients[2,4],
                       ivmod3_white$summary$coefficients[2,4],  ivmod3_black$summary$coefficients[2,4], ivmod3_hispanic$summary$coefficients[2,4],
                       ivmod4_white$summary$coefficients[2,4],  ivmod4_black$summary$coefficients[2,4], ivmod4_hispanic$summary$coefficients[2,4],
                       ivmod5_white$summary$coefficients[2,4],  ivmod5_black$summary$coefficients[2,4], ivmod5_hispanic$summary$coefficients[2,4],
                       ivmod6_white$summary$coefficients[2,4],  ivmod6_black$summary$coefficients[2,4], ivmod6_hispanic$summary$coefficients[2,4],
                       ivmod_rep_white$summary$coefficients[2,4],  ivmod_rep_black$summary$coefficients[2,4], ivmod_rep_hispanic$summary$coefficients[2,4],
                       
                       
                       
                       ivmod1_white_f12$summary$coefficients[2,4],  ivmod1_black_f12$summary$coefficients[2,4], ivmod1_hispanic_f12$summary$coefficients[2,4],
                       ivmod2_white_f12$summary$coefficients[2,4],  ivmod2_black_f12$summary$coefficients[2,4], ivmod2_hispanic_f12$summary$coefficients[2,4],
                       ivmod5_white_f12$summary$coefficients[2,4],  ivmod5_black_f12$summary$coefficients[2,4], ivmod5_hispanic_f12$summary$coefficients[2,4],
                       ivmod6_white_f12$summary$coefficients[2,4],  ivmod6_black_f12$summary$coefficients[2,4], ivmod6_hispanic_f12$summary$coefficients[2,4],
                       ivmod_rep_white_f12$summary$coefficients[2,4],  ivmod_rep_black_f12$summary$coefficients[2,4], ivmod_rep_hispanic_f12$summary$coefficients[2,4]
                       
                       
                       
                        
                        
  )
 
  ##############
  holder$race = c(rep(c("white", "black", "hispanic"), 12))
  
  holder$dv = c(c(rep("Vote 2016", 3),
                 rep("Vote 2014", 3),
                 rep("Vote 2012", 3),
                 rep("Vote 2010", 3),
                 rep("Democrat", 3),
                 rep("Registered", 3),
                 rep("Republican", 3)),
                 
                 c(rep("Vote 2016", 3),
                   rep("Vote 2014", 3),
                   rep("Democrat", 3),
                   rep("Registered", 3),
                   rep("Republican", 3))
                 
                 )
  
  
  holder$endog = c(rep("Vote 2008", 7*3),
                    rep("Vote 2012", 5*3))
  holder$state = state

  
  results = rbind(results, holder)
  
  print(f); print(nrow(results))
}



rm(list=ls()[grepl('mod',ls())])
gc()

# save state-level results for later modeling
write_csv(results,'results/main_state_results.csv')






# all races
ggsave(filename= 'figures/Fig2.pdf', width = 9, height = 5, 
plot = results %>%
  mutate(race=Hmisc::capitalize(race))%>%
  filter(endog=='Vote 2008', grepl('Vote', dv))%>%
  mutate(race = factor(race, levels = c('Hispanic','White',  'Black')))%>%
  mutate( dv = paste(gsub('Vote ', '', dv),' Election')) %>%  
  ggplot(aes(x=coef, y = ..scaled..,weight = 1/(se^2), group = race, linetype = race, fill = race))+
  geom_density(alpha=.5)+
  xlab('State-Level Effects')+
  theme_minimal()+
 guides(fill = guide_legend(reverse = TRUE), linetype = guide_legend(reverse = TRUE))+
  scale_linetype_manual(values = c('dashed', 'dotdash', 'solid'))+
  scale_fill_manual(values = c('grey','white',  'black'))+
  xlim(-0.05,0.45)+
  theme(axis.text.y=element_blank(), axis.title.y=element_blank(), 
        strip.text.x = element_text(face='bold', size =14),strip.text.y = element_text(face='bold', size =14),
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank())+
  facet_wrap(dv ~ ., nrow = 4)
)

ggsave(filename = 'figures/FigS2.pdf', width = 9, height = 5,
plot = results %>%
  mutate(race=Hmisc::capitalize(race))%>%
  filter(endog=='Vote 2012', grepl('Vote', dv))%>%
  mutate(race = factor(race, levels = c('Hispanic','White',  'Black')))%>%
  mutate( dv = paste(gsub('Vote ', '', dv),' Election')) %>%  
  ggplot(aes(x=coef, y = ..scaled..,weight = 1/(se^2), group = race, linetype = race, fill = race))+
  geom_density(alpha=.5)+
  xlab('State-Level Effects')+
  theme_minimal()+
  guides(fill = guide_legend(reverse = TRUE), linetype = guide_legend(reverse = TRUE))+
  scale_linetype_manual(values = c('dashed', 'dotdash', 'solid'))+
  scale_fill_manual(values = c('grey','white',  'black'))+
  xlim(-0.05,0.45)+
  theme(axis.text.y=element_blank(), axis.title.y=element_blank(), 
        strip.text.x = element_text(face='bold', size =14),strip.text.y = element_text(face='bold', size =14),
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank())+
  facet_wrap(dv ~ ., nrow = 2)
)


ggsave(filename = 'figures/FigS4.pdf', width = 9, height = 5, 
plot =results %>%
  mutate(race=Hmisc::capitalize(race),
         dv=factor(dv, levels = c("Vote 2016",   "Vote 2014"  , "Vote 2012" ,  "Vote 2010" , "Registered" , "Democrat" ,   
                                  "Republican", "Major Party")))%>%
  filter(endog=='Vote 2008', race!='Non-black', dv%in%c('Registered', 'Democrat', 'Republican'))%>%
  mutate(race = factor(race, levels = c('Hispanic','White',  'Black')))%>%
  ggplot(aes(x=coef, y = ..scaled..,weight = 1/(se^2), group = race, linetype = race, fill = race))+
  geom_density(alpha=.5)+
  xlab('State-Level Effects')+
  theme_minimal()+
  guides(fill = guide_legend(reverse = TRUE), linetype = guide_legend(reverse = TRUE))+
  scale_linetype_manual(values = c('dashed', 'dotdash', 'solid'))+
  scale_fill_manual(values = c('grey','white',  'black'))+
  xlim(-0.3,1)+
  theme(axis.text.y=element_blank(), axis.title.y=element_blank(), 
        strip.text.x = element_text(face='bold', size =14),strip.text.y = element_text(face='bold', size =14),
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank())+
  facet_wrap(dv ~ ., nrow = 3)
)




### Weighted Average of State CACEs

predictions_white = as.data.frame(matrix(NA, ncol = 5))
predictions_black = as.data.frame(matrix(NA, ncol = 5))
predictions_hispanic = as.data.frame(matrix(NA, ncol = 5))


colnames(predictions_white) = c("ev", "dv", "coef", "se", "race")
colnames(predictions_black) = c("ev", "dv", "coef", "se", "race")
colnames(predictions_hispanic) = c("ev", "dv", "coef", "se", "race")


predictions_white$race = "white"
predictions_black$race = "black"
predictions_hispanic$race = "hispanic"



data = results


for(i in 1:length(unique(data$endog))){
  for(j in 1:length(unique(data$dv))){
    if(length(data$dv[data$dv == unique(data$dv)[j] & data$endog==unique(data$endog)[i]]) > 0){
      
      preds_white = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "white"  & data$dv == unique(data$dv)[j] ], data$se[data$endog == unique(data$endog)[i] & data$race == "white" & data$dv == unique(data$dv)[j]])
      predictions_white = rbind(predictions_white, c(unique(data$endog)[i], unique(data$dv)[j], preds_white$est, preds_white$se, "white"))
      
      preds_black = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "black" & data$dv == unique(data$dv)[j]], data$se[data$endog == unique(data$endog)[i] & data$race == "black" & data$dv == unique(data$dv)[j]])
      predictions_black = rbind(predictions_black, c(unique(data$endog)[i], unique(data$dv)[j], preds_black$est, preds_black$se, "black"))
      
      preds_hispanic = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "hispanic"  & data$dv == unique(data$dv)[j]], data$se[data$endog == unique(data$endog)[i] & data$race == "hispanic" & data$dv == unique(data$dv)[j]])
      predictions_hispanic = rbind(predictions_hispanic, c(unique(data$endog)[i], unique(data$dv)[j], preds_hispanic$est, preds_hispanic$se, "hispanic"))
      
      
      
      
      
    }
    
  }
  
}
meta_plot=rbind(predictions_white, predictions_black, predictions_hispanic)
for(i in 3:(ncol(meta_plot)-2)){
  meta_plot[,i] = as.numeric(meta_plot[,i])
}
meta_plot$se =as.numeric(meta_plot$se)
meta_plot = meta_plot[!is.na(meta_plot$ev),]
meta_plot = meta_plot[!is.nan(meta_plot$coef),]




plt = meta_plot%>%filter(ev == "Vote 2008" & race != "all" & !is.na(race))%>%
  mutate(race = factor(Hmisc::capitalize(race), levels = c('Black', 'White', 'Hispanic')))

ggsave(filename = "figures/Fig3.pdf", width=9,height=5,
plot = ggplot(data = plt[plt$dv %in% c("Vote 2010", "Vote 2012", "Vote 2014", "Vote 2016"),], aes(x = dv, y = coef, color = race, fill = race)) +
  geom_hline(yintercept = 0, linetype = 'dotted', color = 'grey60') +
  geom_point(shape = 21, size = 6, position=position_dodge(.5), alpha = .75) + xlab('') +
  ylab('Effect of 2008 Voting on Future Voting') + 
  geom_errorbar(aes(ymin=coef-1.96*se, ymax=coef+1.96*se, linetype = race), width=0,
                position=position_dodge(.5)) +
  scale_color_manual(values = c("black", "black", "black"))+
  scale_fill_manual(values = c("black", "white", "grey"))+
  scale_linetype_manual(values = c('solid', 'dotdash', 'dashed'))+
  theme_minimal()+
  scale_x_discrete(labels = c("2010", "2012", "2014", "2016"))+
  theme(axis.text.y=element_text(face='bold', size =14), axis.title.y=element_text(face='bold', size =14), 
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank(), legend.key.width=unit(4,"line"))+
  NULL
)

### Table
 results %>% 
   dplyr::filter(dv %in% c('Vote 2010', 'Vote 2012') & endog == 'Vote 2008')%>%
   dplyr::group_by(dv,state)%>%
   dplyr::mutate(bold = as.numeric(race == 'black' & 
                                     `p value` < 0.05 & 
                                     (coef > coef[race == 'white'] | (`p value`[race == 'white'] >= 0.05)) &
                                     (coef > coef[race == 'hispanic'] | (`p value`[race == 'hispanic'] >= 0.05)  )))%>%
   ungroup %>%
  mutate(state = toupper(state), 
         race = Hmisc::capitalize(race),
         coef  = round(coef,3),
         se = round(se,3)
           
  ) %>%
  mutate(
         coef = ifelse(bold == 1, paste0('\\textbf{', coef,'}'), as.character(coef)),
         se = ifelse(bold == 1, paste0('\\textbf{', paste0('(',se,')'),'}'), paste0('(',se,')'))
  )%>%
  select(state, dv, race, coef, se)%>%  
  pivot_wider(names_from = c('dv','race'),
              values_from = c('coef','se'),
              id_cols = 'state')%>%
  select(state, 
         `coef_Vote 2010_White`,
         `se_Vote 2010_White`,
         `coef_Vote 2010_Black`,
         `se_Vote 2010_Black`,
         `coef_Vote 2010_Hispanic`,
         `se_Vote 2010_Hispanic`,
         
         `coef_Vote 2012_White`,
         `se_Vote 2012_White`,
         `coef_Vote 2012_Black`,
         `se_Vote 2012_Black`,
         `coef_Vote 2012_Hispanic`,
         `se_Vote 2012_Hispanic`)%>%
  bind_rows(
    meta_plot %>% 
      dplyr::filter(dv %in% c('Vote 2010', 'Vote 2012') & ev == 'Vote 2008')%>%
      dplyr::group_by(dv)%>%
      dplyr::mutate(bold = as.numeric(race == 'black' & 
                                 (coef > coef[race == 'white'])  &
                                 (coef > coef[race == 'hispanic']) ))  %>%
   ungroup %>%
      mutate(state = 'Meta', 
             race = Hmisc::capitalize(race),
             coef  = round(coef,3),
             se = round(se,3)
             
      ) %>%
      mutate(
        coef = ifelse(bold == 1, paste0('\\textbf{', coef,'}'), as.character(coef)),
        se = ifelse(bold == 1, paste0('\\textbf{', paste0('(',se,')'),'}'), paste0('(',se,')'))
      )%>%
      select( state, dv, race, coef, se)%>%
      pivot_wider(names_from = c('dv','race'),
                  values_from = c('coef','se'),
                  id_cols = 'state')%>%
      select(state, 
             `coef_Vote 2010_White`,
             `se_Vote 2010_White`,
             `coef_Vote 2010_Black`,
             `se_Vote 2010_Black`,
             `coef_Vote 2010_Hispanic`,
             `se_Vote 2010_Hispanic`,
             
             `coef_Vote 2012_White`,
             `se_Vote 2012_White`,
             `coef_Vote 2012_Black`,
             `se_Vote 2012_Black`,
             `coef_Vote 2012_Hispanic`,
             `se_Vote 2012_Hispanic`))%>%
  xtable(digits = 3, align = 'cccccccc|cccccc')%>%
  print(row.names = F, file = 'tables/Tab1.tex')






results %>% 
  dplyr::filter(dv %in% c('Vote 2014', 'Vote 2016') & endog == 'Vote 2008')%>%
  dplyr::group_by(dv,state)%>%
  dplyr::mutate(bold = as.numeric(race == 'black' & 
                                    `p value` < 0.05 & 
                                    (coef > coef[race == 'white'] | (`p value`[race == 'white'] >= 0.05)) &
                                    (coef > coef[race == 'hispanic'] | (`p value`[race == 'hispanic'] >= 0.05)  )))%>%
  ungroup %>%
  mutate(state = toupper(state), 
         race = Hmisc::capitalize(race),
         coef  = round(coef,3),
         se = round(se,3)
  ) %>%
  mutate(
    coef = ifelse(bold == 1, paste0('\\textbf{', coef,'}'), as.character(coef)),
    se = ifelse(bold == 1, paste0('\\textbf{', paste0('(',se,')'),'}'), paste0('(',se,')'))
  )%>%
  select(state, dv, race, coef, se)%>%  
  pivot_wider(names_from = c('dv','race'),
              values_from = c('coef','se'),
              id_cols = 'state')%>%
  select(state, 
         `coef_Vote 2014_White`,
         `se_Vote 2014_White`,
         `coef_Vote 2014_Black`,
         `se_Vote 2014_Black`,
         `coef_Vote 2014_Hispanic`,
         `se_Vote 2014_Hispanic`,
         
         `coef_Vote 2016_White`,
         `se_Vote 2016_White`,
         `coef_Vote 2016_Black`,
         `se_Vote 2016_Black`,
         `coef_Vote 2016_Hispanic`,
         `se_Vote 2016_Hispanic`)%>%
  bind_rows(
    meta_plot %>% 
      dplyr::filter(dv %in% c('Vote 2014', 'Vote 2016') & ev == 'Vote 2008')%>%
      dplyr::group_by(dv)%>%
      dplyr::mutate(bold = as.numeric(race == 'black' & 
                                        (coef > coef[race == 'white'] ) &
                                        (coef > coef[race == 'hispanic']   )))%>%
      ungroup %>%
      mutate(state = 'Meta', 
             race = Hmisc::capitalize(race),
             coef  = round(coef,3),
             se = round(se,3)
             
      ) %>%
      mutate(
        coef = ifelse(bold == 1, paste0('\\textbf{', coef,'}'), as.character(coef)),
        se = ifelse(bold == 1, paste0('\\textbf{', paste0('(',se,')'),'}'), paste0('(',se,')'))
      )%>%
      select( state, dv, race, coef, se)%>%
      pivot_wider(names_from = c('dv','race'),
                  values_from = c('coef','se'),
                  id_cols = 'state')%>%
      select(state, 
             `coef_Vote 2014_White`,
             `se_Vote 2014_White`,
             `coef_Vote 2014_Black`,
             `se_Vote 2014_Black`,
             `coef_Vote 2014_Hispanic`,
             `se_Vote 2014_Hispanic`,
             
             `coef_Vote 2016_White`,
             `se_Vote 2016_White`,
             `coef_Vote 2016_Black`,
             `se_Vote 2016_Black`,
             `coef_Vote 2016_Hispanic`,
             `se_Vote 2016_Hispanic`)
    
  )%>%
  xtable(digits = 3, align = 'cccccccc|cccccc')%>%
  print(row.names = F, file = 'tables/Tab2.tex')

## 2012 effects
plt = meta_plot%>%filter(ev == "Vote 2012" & race != "all" & !is.na(race))%>%
  mutate(race = factor(Hmisc::capitalize(race), levels = c('Black', 'White', 'Hispanic')))

ggsave(filename = "figures/FigS1.pdf", width=9,height=5,
plot = ggplot(data = plt[plt$dv %in% c( "Vote 2014", "Vote 2016"),], aes(x = dv, y = coef, color = race, fill = race)) +
  geom_hline(yintercept = 0, linetype = 'dotted', color = 'grey60') +
  geom_point(shape = 21, size = 6, position=position_dodge(.5), alpha = .75) + xlab('') +
  ylab('Effect of 2012 Voting on Future Voting') + 
  geom_errorbar(aes(ymin=coef-1.96*se, ymax=coef+1.96*se, linetype = race), width=0,
                position=position_dodge(.5)) +
  scale_color_manual(values = c("black", "black", "black"))+
  scale_fill_manual(values = c("black", "white", "grey"))+
  scale_linetype_manual(values = c('solid', 'dotdash', 'dashed'))+
  theme_minimal()+
  scale_x_discrete(labels = c("2014", "2016"))+
  theme(axis.text.y=element_text(face='bold', size =14), axis.title.y=element_text(face='bold', size =14), 
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank(), legend.key.width=unit(4,"line"))+
  NULL
)


## Make Tables 1 and 2

# Table 1: 2010 and 2012 voting outcomes




################## States that record race
plt = results%>%filter(endog == "Vote 2008" & race %in% c('white', 'hispanic', 'black') & !is.na(race) & state %in% c('sc', 'al', 'fl'))%>%
  mutate(race = factor(Hmisc::capitalize(race), levels = c('Black', 'White', 'Hispanic')),
         state = toupper(state))

ggsave(filename = "figures/FigS10.pdf", width=9,height=5,
plot = ggplot(data = plt[plt$dv %in% c("Vote 2010", "Vote 2012", "Vote 2014", "Vote 2016"),], aes(x = dv, y = coef, color = race, fill = race)) +
  geom_hline(yintercept = 0, linetype = 'dotted', color = 'grey60') +
  geom_point(shape = 21, size = 6, position=position_dodge(.5), alpha = .75) + xlab('') +
  ylab('Effect of 2008 Voting on Future Voting') + 
  geom_errorbar(aes(ymin=coef-1.96*se, ymax=coef+1.96*se, linetype = race), width=0,
                position=position_dodge(.5)) +
  scale_color_manual(values = c("black", "black", "black"))+
  scale_fill_manual(values = c("black", "white", "grey"))+
  scale_linetype_manual(values = c('solid', 'dotdash', 'dashed'))+
  theme_minimal()+
  scale_x_discrete(labels = c("2010", "2012", "2014", "2016"))+
  theme(axis.text.y=element_text(face='bold', size =14), axis.title.y=element_text(face='bold', size =14), 
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank(), legend.key.width=unit(4,"line"))+
  facet_wrap(state~., nrow = 3)
)


################## States that record pid
pid.states = read_csv('state_fips.csv')%>%
  filter(record_pid==1)%>%
  pull(state_abbr)%>%
  tolower()


# registration weighted average effect
predictions_white = as.data.frame(matrix(NA, ncol = 5))
predictions_black = as.data.frame(matrix(NA, ncol = 5))
predictions_hispanic = as.data.frame(matrix(NA, ncol = 5))


colnames(predictions_white) = c("ev", "dv", "coef", "se", "race")
colnames(predictions_black) = c("ev", "dv", "coef", "se", "race")
colnames(predictions_hispanic) = c("ev", "dv", "coef", "se", "race")


predictions_white$race = "white"
predictions_black$race = "black"
predictions_hispanic$race = "hispanic"



data = results %>%
  filter(dv=='Registered')


for(i in 1:length(unique(data$endog))){
  for(j in 1:length(unique(data$dv))){
    if(length(data$dv[data$dv == unique(data$dv)[j] & data$endog==unique(data$endog)[i]]) > 0){
      
      preds_white = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "white"  & data$dv == unique(data$dv)[j] ], data$se[data$endog == unique(data$endog)[i] & data$race == "white" & data$dv == unique(data$dv)[j]])
      predictions_white = rbind(predictions_white, c(unique(data$endog)[i], unique(data$dv)[j], preds_white$est, preds_white$se, "white"))
      
      preds_black = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "black" & data$dv == unique(data$dv)[j]], data$se[data$endog == unique(data$endog)[i] & data$race == "black" & data$dv == unique(data$dv)[j]])
      predictions_black = rbind(predictions_black, c(unique(data$endog)[i], unique(data$dv)[j], preds_black$est, preds_black$se, "black"))
      
      preds_hispanic = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "hispanic"  & data$dv == unique(data$dv)[j]], data$se[data$endog == unique(data$endog)[i] & data$race == "hispanic" & data$dv == unique(data$dv)[j]])
      predictions_hispanic = rbind(predictions_hispanic, c(unique(data$endog)[i], unique(data$dv)[j], preds_hispanic$est, preds_hispanic$se, "hispanic"))
      
      
      
      
      
    }
    
  }
  
}
meta_plot=rbind(predictions_white, predictions_black, predictions_hispanic)
for(i in 3:(ncol(meta_plot)-2)){
  meta_plot[,i] = as.numeric(meta_plot[,i])
}
meta_plot$se =as.numeric(meta_plot$se)
meta_plot = meta_plot[!is.na(meta_plot$ev),]
meta_plot = meta_plot[!is.nan(meta_plot$coef),]



plt1 = meta_plot%>%filter(ev == "Vote 2008" )%>%
  mutate(race = factor(Hmisc::capitalize(race), levels = c('Black', 'White', 'Hispanic')))


predictions_white = as.data.frame(matrix(NA, ncol = 5))
predictions_black = as.data.frame(matrix(NA, ncol = 5))
predictions_hispanic = as.data.frame(matrix(NA, ncol = 5))


colnames(predictions_white) = c("ev", "dv", "coef", "se", "race")
colnames(predictions_black) = c("ev", "dv", "coef", "se", "race")
colnames(predictions_hispanic) = c("ev", "dv", "coef", "se", "race")


predictions_white$race = "white"
predictions_black$race = "black"
predictions_hispanic$race = "hispanic"



data = results %>%
  filter(state %in% pid.states & dv !='Registered')


for(i in 1:length(unique(data$endog))){
  for(j in 1:length(unique(data$dv))){
    if(length(data$dv[data$dv == unique(data$dv)[j] & data$endog==unique(data$endog)[i]]) > 0){
      
      preds_white = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "white"  & data$dv == unique(data$dv)[j] ], data$se[data$endog == unique(data$endog)[i] & data$race == "white" & data$dv == unique(data$dv)[j]])
      predictions_white = rbind(predictions_white, c(unique(data$endog)[i], unique(data$dv)[j], preds_white$est, preds_white$se, "white"))
      
      preds_black = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "black" & data$dv == unique(data$dv)[j]], data$se[data$endog == unique(data$endog)[i] & data$race == "black" & data$dv == unique(data$dv)[j]])
      predictions_black = rbind(predictions_black, c(unique(data$endog)[i], unique(data$dv)[j], preds_black$est, preds_black$se, "black"))
      
      preds_hispanic = meta.maker(data$coef[data$endog == unique(data$endog)[i] & data$race == "hispanic"  & data$dv == unique(data$dv)[j]], data$se[data$endog == unique(data$endog)[i] & data$race == "hispanic" & data$dv == unique(data$dv)[j]])
      predictions_hispanic = rbind(predictions_hispanic, c(unique(data$endog)[i], unique(data$dv)[j], preds_hispanic$est, preds_hispanic$se, "hispanic"))
      
      
      
      
      
    }
    
  }
  
}
meta_plot=rbind(predictions_white, predictions_black, predictions_hispanic)
for(i in 3:(ncol(meta_plot)-2)){
  meta_plot[,i] = as.numeric(meta_plot[,i])
}
meta_plot$se =as.numeric(meta_plot$se)
meta_plot = meta_plot[!is.na(meta_plot$ev),]
meta_plot = meta_plot[!is.nan(meta_plot$coef),]



plt2 = meta_plot%>%filter(ev == "Vote 2008" )%>%
  mutate(race = factor(Hmisc::capitalize(race), levels = c('Black', 'White', 'Hispanic')))

plt = rbind(plt1,plt2)

ggsave(filename = "figures/FigS3.pdf", width=9,height=5,
plot = ggplot(data = plt[plt$dv %in% c("Registered", 'Democrat', 'Republican'),]%>%
         mutate(dv = factor(dv, levels = c('Registered', 'Democrat', 'Republican'))), aes(x = dv, y = coef, color = race, fill = race)) +
  geom_hline(yintercept = 0, linetype = 'dotted', color = 'grey60') +
  geom_point(shape = 21, size = 6, position=position_dodge(.5), alpha = .75) + xlab('') +
  ylab('Effect of 2008 Voting on Registration') + 
  geom_errorbar(aes(ymin=coef-1.96*se, ymax=coef+1.96*se, linetype = race), width=0,
                position=position_dodge(.5)) +
  scale_color_manual(values = c("black", "black", "black"))+
  scale_fill_manual(values = c("black", "white", "grey"))+
  scale_linetype_manual(values = c('solid', 'dotdash', 'dashed'))+
  theme_minimal()+
  scale_x_discrete(labels = c("Registered", "Democrat", 'Republican'))+
  theme(axis.text.y=element_text(face='bold', size =14), axis.title.y=element_text(face='bold', size =14), 
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank(), legend.key.width=unit(4,"line"))+
  NULL
)

ggsave(filename = 'figures/FigS4.pdf', width = 9, height = 5, 
plot = results %>%
  mutate(race=Hmisc::capitalize(race),
         dv=factor(dv, levels = c("Vote 2016",   "Vote 2014"  , "Vote 2012" ,  "Vote 2010" , "Registered" , "Democrat" ,   
                                  "Republican", "Major Party")))%>%
  filter(endog=='Vote 2008', race!='Non-black', dv%in%c('Registered', 'Democrat', 'Republican'))%>%
  mutate(race = factor(race, levels = c('Hispanic','White',  'Black')),
         coef = ifelse(dv %in% c('Democrat', 'Republican') & !state %in% pid.states, NA, coef),
         se = ifelse(dv %in% c('Democrat', 'Republican') & !state %in% pid.states, NA, se))%>%
  ggplot(aes(x=coef, y = ..scaled..,weight = 1/(se^2), group = race, linetype = race, fill = race))+
  geom_density(alpha=.5)+
  xlab('State-Level Effects')+
  theme_minimal()+
  guides(fill = guide_legend(reverse = TRUE), linetype = guide_legend(reverse = TRUE))+
  scale_linetype_manual(values = c('dashed', 'dotdash', 'solid'))+
  scale_fill_manual(values = c('grey','white',  'black'))+
  xlim(-0.3,1)+
  theme(axis.text.y=element_blank(), axis.title.y=element_blank(), 
        strip.text.x = element_text(face='bold', size =14),strip.text.y = element_text(face='bold', size =14),
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank())+
  facet_wrap(dv ~ ., nrow = 3)
)



ggsave(filename = "figures/FigS24.pdf", width=9,height=5,
plot = ggplot(data = plt2[plt2$dv %in% c("Vote 2010", "Vote 2012", "Vote 2014", "Vote 2016"),], aes(x = dv, y = coef, color = race, fill = race)) +
  geom_hline(yintercept = 0, linetype = 'dotted', color = 'grey60') +
  geom_point(shape = 21, size = 6, position=position_dodge(.5), alpha = .75) + xlab('') +
  ylab('Effect of 2008 Voting on Future Voting') + 
  geom_errorbar(aes(ymin=coef-1.96*se, ymax=coef+1.96*se, linetype = race), width=0,
                position=position_dodge(.5)) +
  scale_color_manual(values = c("black", "black", "black"))+
  scale_fill_manual(values = c("black", "white", "grey"))+
  scale_linetype_manual(values = c('solid', 'dotdash', 'dashed'))+
  theme_minimal()+
  scale_x_discrete(labels = c("2010", "2012", "2014", "2016"))+
  theme(axis.text.y=element_text(face='bold', size =14), axis.title.y=element_text(face='bold', size =14), 
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank(), legend.key.width=unit(4,"line"))+
  NULL
)


ggsave(filename = 'figures/FigS25.pdf', width = 9, height = 5, 
plot = data %>%
  mutate(race=Hmisc::capitalize(race))%>%
  filter(endog=='Vote 2008', grepl('Vote', dv))%>%
  mutate(race = factor(race, levels = c('Hispanic','White',  'Black')))%>%
  mutate( dv = paste(gsub('Vote ', '', dv),' Election')) %>%  
  ggplot(aes(x=coef, y = ..scaled..,weight = 1/(se^2), group = race, linetype = race, fill = race))+
  geom_density(alpha=.5)+
  xlab('State-Level Effects')+
  theme_minimal()+
  guides(fill = guide_legend(reverse = TRUE), linetype = guide_legend(reverse = TRUE))+
  scale_linetype_manual(values = c('dashed', 'dotdash', 'solid'))+
  scale_fill_manual(values = c('grey','white',  'black'))+
  xlim(-0.05,0.45)+
  theme(axis.text.y=element_blank(), axis.title.y=element_blank(), 
        strip.text.x = element_text(face='bold', size =14),strip.text.y = element_text(face='bold', size =14),
        axis.text.x = element_text(face="bold", size =14), legend.text=element_text(face='bold', size =14),
        legend.position="bottom", legend.spacing.x = unit(.25, 'cm'),legend.title = element_blank())+
  facet_wrap(dv ~ ., nrow = 4)
)





